(function (window, $) {

    $(function () {
        // 设置iframe的高度，非精准适应屏幕高度
        var docHeight = $(document).height();
        $('#reportContainer, #applicationContainer').height(docHeight - 300);


        var cardModel = [
            {type: "1", name: "身份证"},
            {type: "2", name: "户口簿"},
            {type: "3", name: "护照"},
            {type: "4", name: "军官证"},
            {type: "5", name: "士兵证"},
            {type: "6", name: "港澳居民来往内地通行证"},
            {type: "7", name: "台湾同胞来往内地通行证"},
            {type: "8", name: "临时身份证"},
            {type: "9", name: "外国人居住证"},
            {type: "10", name: "警官证"},
            {type: "11", name: "香港身份证"},
            {type: "12", name: "澳门身份证"},
            {type: "13", name: "台湾身份证"},
            {type: "14", name: "其他证件"}
        ];
        var typesModel = [{type: 1, name: "个人简单版"},
            {type: 2, name: "个人明细版"},
            {type: 3, name: "股指期货版"}];

        var timeFlag = false;

        var vm = avalon.define({
            $id: 'agentInquiryPage',
            cardModel: cardModel,
            typesModel: typesModel,
            firstStepVo: {},
            reqReportVo:{},
            errMsg: {},
            inquiryModel: {
                id: '',
                cardType: 1,
                cardNum: '',
                userName: '',
                agentCardType: 1,
                agentCardNum: '',
                agentName: '',
                phone:'',
                format: 2,
                faceImage:{id:'', path:'resources/skins/img/img5.jpg'},
                sceneImgUrl:'',
                cardImgUrl:'',
                agentCardImgUrl:'',
                otherImgUrl: ''
                	
            },
            application: {
                content: ''
            },
            chargeVo: {
            	chargeNo: '',
            	isPayFee: 0
            },
            report: {
                content: ''
            },
            dissentid: '',
            cardPic: [],
            otherPic: [],
            agentPic:[],
            step: 1,
            manualFaceVerify: false,
            showError: function (reasons) {
                console.log("reasons:", reasons);
                var result = {};
                for (var i = 0; i < reasons.length; i++) {
                    var reason = reasons[i];
                    var element = reason.element;
                    var name = element.id;
                    if (name) {
                        result[name] = reason;
                    }
                }
                
                vm.errMsg = result;
            },
            preStep : function(step){
            	vm.step = step;
            },
            gotoStep: function (step) {
            	console.log('step:', step);
                if(step==2){
                	
                    var imgList=vm.cardPic.concat(vm.agentPic).concat(vm.otherPic);
                    console.log('imgList:', imgList);
                    if(imgList.length>0){
                        vm.uploadPhoto(imgList,vm.uploadCallback,2);
                        return;
                    }else{
                        Camera.destroy();
                        Camera.init({
                            container: '#faceLeft',
                            id: 'ca',
                            width:280,
                            height:200,
                            viewWidth:240,
                            viewHeight:180,
                            type:2,
                            facRect:false
                        });
                    }
                }
                if(step==3){
                    var imgList=new Array(vm.inquiryModel.faceImage);
                    vm.uploadPhoto(imgList,vm.uploadCallback,2);
                    $("#faceLeft").html("");
                    console.log("faceLeft:", "清空faceLeft内容");
                    return;
                }
                vm.step = step;
                // if (vm.step >= 3) {
                //     vm.submit();
                // }

            },
            verifyFace: function () {
                // 应该还有自动人脸识别
                if (vm.manualFaceVerify) {
                    vm.gotoStep(3);
                } else {
                    alert('请进行人证识别审核');
                }
            },
            waitApprove: function(){
                vm.gotoStep(6);
                if(timeFlag) return;
                $.ajax({
                    url: 'inquiry/detail?id=' + vm.inquiryModel.id + "&t=" + Date.parse(new Date()),
                    type: 'get',
                    async: false,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            if(resp.data.status == 1){
                                timeFlag = true;
                                $("#waitTip").css("display","none");
                                $('#reportDiv').css("display","");
                                vm.inquiryCreditReport();
                            }
                            if(resp.data.status == 4){
                                timeFlag = true;
                                $("#waitTip").html("审核失败");
                            }
                        } else {
                            timeFlag = true;
                        }
                    },
                    error: function(){
                        timeFlag = true;
                    }
                });

                window.setTimeout(function () {
                    vm.waitApprove();
                }, 2000);
            },

            readIdCard: function () {
                var data = Camera.readIdCardData();

                if (data) {
                    vm.inquiryModel.userName = data.name;
                    vm.inquiryModel.cardNum = data.id;
                }
            },
            readAgentIdCard: function () {
                var data = Camera.readIdCardData();

                if (data) {
                    vm.inquiryModel.agentName = data.name;
                    vm.inquiryModel.agentCardNum = data.id;
                }
            },
            
            charge: function (type) {

            	if(type == 1){
                	if(vm.firstStepVo.isFee == 0 ||  vm.chargeVo.isPayFee == 1){
                		console.log("缴费：","不需交费或已缴费，不提交后台，非正常操作");
                		return ;
                	}
                }
            	
            	if(type == -1 && vm.chargeVo.isPayFee == 0){
            		console.log("撤销缴费：","不需缴费或未缴费，不提交后台，非正常操作");
            		return ;
            	}
                //user=%E8%AE%B8%E5%BA%86%E8%BE%89&ctype=0&idno=440111199302210335&querytype=21
                //&reltel=&relname=&relcerttype=&relcertno=&forwardtype=1
                
                var url = "inquiry/charge";
                var msg = "请确认此人已经缴费，再进行此操作！";
                var tip = "查询缴费";
                
                var data = {};
                if(type == 1){
                	
                	data.user = vm.inquiryModel.userName;
                    data.ctype = vm.inquiryModel.cardType;
                    data.idno = vm.inquiryModel.cardNum;
                    data.reltel = vm.inquiryModel.phone;
                    data.relcerttype = vm.inquiryModel.agentCardType;
                    data.relcertno = vm.inquiryModel.agentCardNum;
                    data.relname = vm.inquiryModel.agentName;
                	data.id= vm.inquiryModel.id;
                    data.querytype = vm.firstStepVo.querytype;
                	data.forwardtype = 1;
                }
                
                if(type == -1){
                	
                	//{chargeNO:"+ chargeNo +",updatetype:\"2\",forwardtype:\"2\"}
                	data.id= vm.inquiryModel.id;
                	data.chargeNo = vm.chargeVo.chargeNo;
                	data.updatetype = 2;
                	data.forwardtype = 2;
                	url = "inquiry/charge/cancel";
                	msg =  "确定要撤销此人的已缴费信息吗？";
                	tip = "撤销缴费";
                }
                
                layer.confirm(msg, {
      			  btn: ['取消','确定'] //按钮
      			}, function(){
      				layer.msg('已取消', {time: 1000 });
      			}, function(){
      				$.ajax({
      					type : "post", // 提交方式
      					url : url,// 路径
      					data : data,// 数据，这里使用的是Json格式进行传输
      					dataType:"json",
      					success : function(result) {// 返回数据根据结果进行相应的处理
      						
      						if (result.code == "SUCCESS") {
      							
      							if(type == 1){
      								
      								vm.chargeVo.chargeNo = result.data.chargeNo;
      								vm.chargeVo.isPayFee = 1;
      								$("#cancelChargeBtn").removeClass("grey");
      								$("#chargeBtn").addClass("grey");
      							}
      							
      							if(type == -1){
      								
      								$("#chargeBtn").removeClass("grey");
      								$("#cancelChargeBtn").addClass("grey");
      								vm.chargeVo.isPayFee = 0;
      								vm.chargeVo.chargeNo = '';
      							}
      							alert(tip + "成功");
      						
      						} else {
      							if(result.code == 'SID_CHECK_FAIL'){
          							location.href = result.data;
          							return;
          						}
      							alert(tip + "失败");
      							return;
      						}
      					}
      				});
      			});
                
                // if (vm.step >= 3) {
                //     vm.submit();
                // }

            },
            //到收费界面
            inquiryToPayment: function () {
                var data = vm.inquiryModel.$model;
                $.ajax({
                    url: 'inquiry/agent/save',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.gotoStep(4);
                            vm.firstStepVo = resp.data.firstStepVo;
                            vm.inquiryModel.id = resp.data.id;
                        } else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    }
                });
            },
            //到申请表界面
            inquiryToApplyTbl: function () {
            	
            	if(vm.firstStepVo.isFee == 1 &&  vm.chargeVo.isPayFee == 0){
            		
            		console.log("缴费：","该用户需要交费，请收费成功后在点击下一步操作");
            		
            		layer.msg('本次查询需要缴费，请点击确认缴费按钮', {time: 2000 });
            		
            		return ;
            	}
            	
                var firstStepVo = vm.firstStepVo.$model;
                var data = {};
                data.querylog = firstStepVo.queryLog;
                data.queryreason = '04';
                data.chargestathidden = firstStepVo.chargeStat;
                data.querytypehidden = firstStepVo.querytype;
                data.querynumber = firstStepVo.queryNum;
                data.historychargestat = firstStepVo.historyChargeStat;
                data.name=vm.inquiryModel.userName;
                data.certtype = vm.inquiryModel.cardType;
                data.certno = vm.inquiryModel.cardNum;
                data.relcerttype = vm.inquiryModel.agentCardType;
                data.relcertno = vm.inquiryModel.agentCardNum;
                data.relname = vm.inquiryModel.agentName;
                data.id= vm.inquiryModel.id;
                data.querytype = firstStepVo.querytype;
                data.reltel = vm.inquiryModel.phone;
                if(vm.chargeVo.chargeNo != ''){
                	data.chargeNOHidden = vm.chargeVo.chargeNo;
                }
                
                
                signIframe.initCreateContainer("userNameSignTd", "userNameSignIframe", 350, 120)
                //querylog=yes&
                //queryreason=04&chargeNOHidden=&dissentid=&chargestathidden=&querytypehidden=24&querynumber=1&historychargestat=0
                //&name=%C1%F5%D0%CB%C3%DC&certtype=0&certno=412822198212021417&reltel=&relname=&relcerttype=&relcertno=&querytype=24
                $.ajax({
                    url: 'inquiry/apply/table',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.reqReportVo = resp.data;
                             vm.reqReportVo.html = "";
                            vm.gotoStep(5);
                            // vm.application.content = resp.data.html;
                            
                            var html = resp.data.html;
                            
                            var ifrDoc = $('#applicationContainer')[0].contentDocument;
                            ifrDoc.body.innerHTML= "";
                            ifrDoc.body.innerHTML = html;
                            ifrDoc.body.style.cssText = 'background-color: #ffffff;';
                            //inquiryUtil.appendSignScript(ifrDoc);
                            //console.log('vm.inquiryModel.phone:', vm.inquiryModel.phone);
//                            if(vm.inquiryModel.phone != null){
//                            	$('#applicationContainer')[0].contentDocument.getElementById("userphone").innerHTML= vm.inquiryModel.phone;
//                            }
                            $('#applicationContainer').css("height", 500);
                        } else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    }
                });
            },

            signHanlder: function (type) {
                // 签名控制
            	if(type == 1){//切换到签名屏
            		document.getElementById("rightDiv").scrollTop = document.body.scrollHeight;
            		hw.switchSignMonitor();
            		$("#PCMonitorLabel").css("display","");
            		$("#signMonitorLabel").css("display","none");      		
            		$("#pcDiv").css("display","none");
            		$("#menuListDiv").css("display","none");
            		return ;
            	}
            	
            	if(type == 2){//切换到PC
            		
            		hw.switchPCMonitor();
            		$("#PCMonitorLabel").css("display","none");
            		$("#signMonitorLabel").css("display","");
            		$("#menuListDiv").css("display","");
            		$("#pcDiv").css("display","");
            		
            		var base64Sign = hw.base64Img();            		
            		console.log('base64Sign:', base64Sign);
            		if(base64Sign != undefined && base64Sign != ""){
            		
	            		$('#applicationContainer')[0].contentDocument.getElementById("userNameImg").style.display="";
	            		$('#applicationContainer')[0].contentDocument.getElementById("userNameImg").src = "data:image/png;base64," + base64Sign;
            	    }
            		
            		return ;
            	}
            	
            },
            phoneHanlder : function(type){
            	// 签名控制
            	if(type == 1){//切换到签名屏
            		//document.getElementById("rightDiv").scrollTop = document.body.scrollHeight;
            		
            		$("#phone").focus();            		
            		$('#ca')[0].contentDocument.getElementById("view1").style.display="none";
            		$("#cameraDiv").css("display","none");
            		$("#menuListDiv").css("display","none");
            		
            		hw.switchSignMonitor();          		
            		
            		return ;
            	}

            },
            printApplyTbl: function () {
                // window.print();
                // 这里需要弹框出来提示 完成 / 重新打印
                commonPrint('applicationContainer');
                // $('#applicationContainer')[0].contentWindow.print();
            },

            inquiryCreditReport: function () {
            	
            	inquiryUtil.saveSign(vm.inquiryModel.id, hw.base64Img());            	             	 
           	    //hw.finalize();
           	    
                //branchquery/dissentInnerQueryActionV2.do?name=������&certtype=0&certno=412822198212021417&vertype=24
                //&dissentid=201706024401240400050_c5d7b54d717ec68e0e466fbc7a7adffb&queryreason=04&chargeNO=G2017060200000105705131
                var data = vm.reqReportVo.$model;
                data.name = vm.inquiryModel.userName;
                data.certno = vm.inquiryModel.cardNum;
                data.id= vm.inquiryModel.id;
                data.queryreason = "04";
                data.certtype = vm.inquiryModel.cardType;
                if(vm.chargeVo.chargeNo != ''){
                	data.chargeNO = vm.chargeVo.chargeNo;
                }
                //data.dissentid
                
                $.ajax({
                    url: 'inquiry/credit/report',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.gotoStep(6);
                            // vm.report.content = resp.data.html;
                            $('#reportContainer')[0].contentDocument.body.innerHTML = resp.data.html;
                            $('#reportContainer')[0].contentDocument.body.style.cssText = 'background-image:url(resources/images/pbccrc_watermark.gif);background-repeat:repeat;background-color: #ffffff;';
                            forbidLeftAndTop.forbid();
                        }  else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    }
                });
            },
            printReport: function () {
                // window.print();
                // 这里需要弹框出来提示 完成 / 重新打印
                if (confirm("你确定要打印该报告吗？")) {
                    var data = {};

                    data.id = vm.inquiryModel.id;
                    data.printResult = 1;
                    $.ajax({
                        url: 'inquiry/credit/print',
                        type: 'post',
                        data: data,
                        dataType:"json",
                        success: function (resp) {
                            if (resp.code === 'SUCCESS') {
                                window.commonPrint('reportContainer');
                                // $('#reportContainer')[0].contentWindow.print();
                            }
                        }
                    });
                } else {
                    //alert("点击了取消");
                }


            },
            cancelPrintReport: function (flag) {
                
            	//打印结果(0：未打印，-1-取消打印， 1-成功，2-失败)
            	var printResult = -1;
            	var msg = "你确定要取消打印吗？";
            	if(flag == 2){
            		msg = "你确定打印完成并返回吗？";
            		printResult = 1;
            	}
            	if(flag == 3){
            		msg = "你确定打印失败并返回吗？";
            		printResult = 2;
            	}
            	
                if (confirm(msg)) {
                	if(printResult != 1){
                		var data = {};

                        data.id = vm.inquiryModel.id;
                        data.printResult = printResult;
                        $.ajax({
                             url: 'inquiry/credit/print',
                             type: 'post',
                             data: data,
                             dataType:"json",
                             success: function (resp) {

                             }
                        });
                                               
                	}
                	forbidLeftAndTop.cancel();
                    // 跳转到初始界面
                    //menuFullUrl('inquiry/agent');
                	location.href="index?sid=" + sid + "&showMenu=AGENT_QUERY_A";
                }

                
            },
            submit: function () {
                // 提交数据并跳转到第四步
                var card = vm.inquiryModel.cardType;
            },
            isIdCard:function(type){
                if(type==1){
                    return vm.inquiryModel.cardType == 1;
                }else{
                    return vm.inquiryModel.agentCardType == 1;
                }
            },
            scan: function (type,deviceType) {
                if(type==1||type==3){
                    if(vm.isIdCard()){
                        var data=Camera.readIdCardData();
                        if(type==1){
                        	vm.cardPic.push({id:"",path:data.front});
                            vm.cardPic.push({id:"",path:data.back});
                        } else {
                        	vm.agentPic.push({id:"",path:data.front});
                            vm.agentPic.push({id:"",path:data.back});
                        }
                        
                    }else{
                        var img = Camera.scan(deviceType);
                        vm.cardPic.push({id:"",path:img});
                    }
                }else if(type==4){
                    vm.inquiryModel.faceImage.path=Camera.scan(1);
                    console.log("vm.inquiryModel.faceImage.path..."+vm.inquiryModel.faceImage.path);
                }else{
                    var img = Camera.scan(deviceType);
                    vm.otherPic.push({id:"",path:img});
                }
            },
            removePic: function (index, type) {
                if (type == 2) {
                    vm.otherPic.splice(index, 1);
                } else {
                    vm.cardPic.splice(index, 1);
                }
            },
            uploadPhoto:function (imgList,callback,sourceType){
                var prefix = 'data:image/png;base64,'; // 注意图片格式
                var prefix1 = 'data:image/jpeg;base64,'; // 注意图片格式
                var vo={};
                if(sourceType==''||sourceType==null){
                    vo.sourceType=2;
                }else{
                    vo.sourceType=sourceType;
                }
                var targetList=[];
                if(imgList.length<1){
                    callback({});
                }else{
                    for(var i=0;i<imgList.length;i++){
                        targetList.push(imgList[i].path.replace(prefix,"").replace(prefix1,""));
                    }
                    vo.base64Files=targetList;
                    $.ajax({
                        url: 'file/upload/base64',
                        data: JSON.stringify(vo),
                        contentType: "application/json; charset=UTF-8",
                        type: "POST",
                        dataType:"json",
                        success: function (responseJSON) {
                            callback(responseJSON);
                        },
                        error:function(){
                            alert("上传失败");
                        }
                    });
                }
                return true;
            },
            uploadCallback:function(data){
                if(vm.step==1){
                    if(data.code=='SUCCESS'){
                        var cardPicSize=vm.cardPic.length;
                        var agentSize=cardPicSize+vm.agentPic.length;
                        var otherSize=agentSize+vm.otherPic.length;
                        var arrayIndex=0;
                        
                        for(var i=0;i<data.data.length;i++){
                            if(i<cardPicSize){
                            	
                                var fileId = data.data[i].id;
                            	vm.inquiryModel.cardImgUrl += fileId + ";"
                            	vm.cardPic[arrayIndex].id=fileId;
                                arrayIndex+=1;
                                continue;
                            }
                            arrayIndex=0;
                            if(i<agentSize){
                            
                            	var agentFileId = data.data[i].id;
                            	vm.inquiryModel.agentCardImgUrl += agentFileId + ";"
                                vm.agentPic[arrayIndex].id=agentFileId;
                                arrayIndex+=1;
                                continue;
                            }
                            arrayIndex=0;
                            if(i<otherSize){
                            
                            	var otherFileId = data.data[i].id;
                            	vm.inquiryModel.otherImgUrl += otherFileId + ";"
                            	vm.otherPic[arrayIndex].id = otherFileId;
                                arrayIndex+=1;
                                continue;
                            }
                        }
                        vm.step=2;
                        Camera.destroy();
                        Camera.init({
                            container: '#faceLeft',
                            id: 'ca',
                            width:280,
                            height:200,
                            viewWidth:240,
                            viewHeight:180,
                            device:"resources/js/camera/device.html",
                            type:2,
                            facRect:false
                        });
                    }else{
                    	if(data.code == 'SID_CHECK_FAIL'){
  							location.href = data.data;
  							return;
  						}
                        alert("文件上传失败");
                    }
                }else if(vm.step==2){
                    vm.inquiryModel.sceneImgUrl=data.data[0].id;
                    vm.step=3;
                }
            },
            validate: {
                onManual: $.noop,
                onValidateAll: function(reasons){
                    console.log("xxxxxxxx");
                    vm.showError(reasons);
                    console.log("xxxxxxxx1");
                    if (!reasons.length) {
                        vm.gotoStep(2);
                    }
                },

                onError: function (reasons, ev) {
                    vm.showError(reasons);
                },
                onSuccess: function (reasons, ev) {
                    vm.errMsg = '';
                },
                // onComplete: avalon.noop,//针对单个表单元素
                // onReset: avalon.noop, //针对单个表单元素
                // validateInBlur: true, // {Boolean} true，在blur事件中进行验证,触发onSuccess, onError, onComplete回调
                // validateInKeyup: true, // {Boolean} true，在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
                validateAllInSubmit: false // {Boolean} true，在submit事件中执行onValidateAll回调
                // resetInFocus: true, // {Boolean} true，在focus事件中执行onReset回调,
                // deduplicateInValidateAll: false // {Boolean} false，在validateAll回调中对reason数组根据元素节点进行去重
            },
            validate2: {
                onManual: $.noop,
                onValidateAll: function(reasons){
                    vm.showError(reasons);
                    if (!reasons.length) {
                        vm.inquiryCreditReport();
                    }
                },

                onError: function (reasons, ev) {
                    vm.showError(reasons);
                },
                onSuccess: function (reasons, ev) {
                    vm.errMsg = '';
                },
                // onComplete: avalon.noop,//针对单个表单元素
                // onReset: avalon.noop, //针对单个表单元素
                // validateInBlur: true, // {Boolean} true，在blur事件中进行验证,触发onSuccess, onError, onComplete回调
                // validateInKeyup: true, // {Boolean} true，在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
                validateAllInSubmit: false // {Boolean} true，在submit事件中执行onValidateAll回调
                // resetInFocus: true, // {Boolean} true，在focus事件中执行onReset回调,
                // deduplicateInValidateAll: false // {Boolean} false，在validateAll回调中对reason数组根据元素节点进行去重
            },
        });
        avalon.scan($("#page-content-wrapper")[0]);
        window.setTimeout(function () {
            Camera.destroy();
            Camera.init({
                container: '#videoContainer',
                id: 'ca',
                width:500,
                height:420,
                viewWidth:500,
                viewHeight:375,
                type: 5
            });

        }, 1000);
    });

}(window, jQuery));